<template>
  <el-dialog
      title="添加用户"
      v-model="data.visible"
      width="50%"
      destroy-on-close
  >
    <el-transfer
        v-model="data.sel"
        filterable
        :titles="['待选列表', '已选列表']"
        filter-placeholder="请出入用户名"
        :data="data.userList"
    />
    <el-row :gutter="24">
      <el-col :span="20"/>
      <el-col>
        <el-button round type="primary" @click="submit">确定</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import {getCurrentInstance, reactive, ref, watch} from "vue";
import {ElMessage} from "element-plus";

export default {
  name: "UserRelationDialog",
  setup() {
    const {proxy} = getCurrentInstance()
    const data = reactive({
      relation: ref(),
      userList: ref([]),
      sel: ref([]),
      //1租户2应用
      dataType: ref(1),
      visible:ref(false)
    })

    const setDialogType = (param)=>{
      proxy.data.dataType=param.type
      proxy.data.relation=param.id
      getUserList(param)
      proxy.data.visible=true
    }

    function getUserList(param){
      proxy.$service.getUserRelationList({
        id:proxy.data.relation,
        type:param.type
      }).then(result=>{
        result.res.data.forEach((item,index)=>{
          proxy.data.userList.push({
            key:item.id,
            label:item.username,
          })
          if (item.checked){
            proxy.data.sel.push(index+1)
          }
        })
        console.log(proxy.data.sel)
      })
    }

    watch(()=>data.visible,(item1,item2)=>{
        if (!item1){
          console.log('item1 ====',item1)
          proxy.data.userList=ref([])
          proxy.data.sel=ref([])
        }
    })

    const filterMethod = (query, item) => {
      console.log("query=== ",query,"---item ",item)
      return item.indexOf(query) > -1
    }

    const submit = () => {
      let type = proxy.data.dataType
      if (type === 1) {
        addTenantUser()
      } else {
        addAppUser()
      }
    }

    function addTenantUser() {
      proxy.$service.addTenantUser({
        tenantId: proxy.data.relation,
        userIds: proxy.data.sel
      }).then(result => {
        if (result.res.code === 0) {
          ElMessage.success({
            message: result.res.msg,
            type: 'success',
          })
          proxy.data.visible=false
        } else {
          ElMessage.error(result.res.msg)
        }
      })
    }

    function addAppUser() {
      proxy.$service.addAppUser({
        appId: proxy.data.relation,
        userIds: proxy.data.sel
      }).then(result => {
        if (result.res.code === 0) {
          ElMessage.success({
            message: result.res.msg,
            type: 'success',
          })
          proxy.data.visible=false
        } else {
          ElMessage.error(result.res.msg)
        }
      })
    }


    return {data, submit,filterMethod,setDialogType}

  }
}
</script>

<style scoped>

</style>